package master;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;

import common.JobObject;
import common.JobsPackage;

public class MasterGUI extends javax.swing.JFrame{
	private final MasterService masterService;
	private JTable jTable1;
	 private JButton jButton1;
	private JScrollPane jScrollPane1;
	
	MasterGUI(MasterService masterService) {
		this.masterService = masterService;
		this.setTitle("Master Info Service");
		initComponents();
		
	}
	
	private void initialButton() {

        jButton1 = new JButton();
        jButton1.setText("Refresh");
        
        jButton1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                refresh();
            }
        });
        //Get Results anytime
        /*// If there exists s Job hasn't finished, then disabled the "Get Result" button.
        for (JobObject job : client.jp.getJobs()) {
            if ("WAITING".equals(job.getStatus()) || "RUNNING".equals(job.getStatus())) {
                jButton2.setEnabled(false);
                break;
            }
        }*/
    }
	
	private void initComponents() {

		jTable1 = new JTable();
        jScrollPane1 = new JScrollPane();
        //setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        jScrollPane1.setName("jScrollPane1");
        
        //this.initialLabel();
        this.initialButton();
        this.initialTable();
        //Timer timer = new Timer(this);
        //timer.start();

        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 656, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(274, 274, 274)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addContainerGap())
        );

        pack();
    }
	
	private void initialTable() {
        ArrayList<String> clientIDs = new ArrayList<String>();
        ArrayList<Integer> jobIDs = new ArrayList<Integer>();
        jTable1.setName("jTable1");
        jScrollPane1.setViewportView(jTable1);
        Iterator<String> iter = masterService.jobPackageInfo.keySet().iterator();
        int numItems = 0;
        while (iter.hasNext()) {
        	numItems += masterService.jobPackageInfo.get(iter.next()).getNumberOfJobs();
        }
        iter = masterService.jobPackageInfo.keySet().iterator();
        Object[][] objects = new Object[numItems][5];
        int acc = 0;
        while (iter.hasNext()) {
	        JobsPackage jp = masterService.jobPackageInfo.get(iter.next());
        	List<JobObject> list = jp.getJobs();
	        
	        for (int i = 0; i < list.size(); i++) {
	            // Create a line object, each line contains four elements.
	            Object[] line = new Object[5];
	            
	            // Assign the value to the line object.
	            line[0] = String.valueOf(list.get(i).getClientID());
	            line[1] = String.valueOf(list.get(i).getJobID());
	            line[2] = String.valueOf(list.get(i).getExecuteFileName());
	            line[3] = String.valueOf(list.get(i).getStatus());
	            // Create a button.
	            JButton killButton = new JButton("Kill Job");
	            line[4] = killButton;
	            
	            // Set the properties of the button.
	            killButton.setName(String.valueOf(list.get(i).getJobID()));
	            killButton.setText("Kill Job");
	            
	            // If this job hasn't finished,then disable the "Kill Job" button.
	            if ("COMPLETED".equals(list.get(i).getStatus())) {
	                killButton.setEnabled(false);
	            }
	            
	            objects[acc+ i] = line;
	            clientIDs.add(list.get(i).getClientID());
	            jobIDs.add(list.get(i).getJobID());
	        }
	        
	        acc += list.size();
	        
	        
	    }
	    jTable1.setModel(new javax.swing.table.DefaultTableModel(objects, new String[] { "CLIENT ID", "JOB ID", "JOB NAME", "STATE",
        "ACTION" }));
	    jTable1.getColumn("ACTION").setCellRenderer(new MyRender(clientIDs, jobIDs, masterService));
    }
	
	
    public void refresh() {
    	initialTable();

    }
    
}
/*
class Timer extends Thread {
	private MasterGUI masterGUI;
	public Timer (MasterGUI masterGUI) {
		this.masterGUI = masterGUI;
	}
	public void run() {
		while (true) {
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			masterGUI.refresh();
		}
	}
}
*/
/*class MyRender extends JButton implements TableCellRenderer {

	ArrayList<String> clientIDs; 
	ArrayList<Integer> jobIDs;
	MasterService masterService;
	public MyRender(ArrayList<String> clientIDs, ArrayList<Integer> jobIDs, MasterService masterService) {
		super();
		this.clientIDs = clientIDs;
		this.jobIDs = jobIDs;
		this.masterService = masterService;
    }

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
            int row, int column) {
        JButton myButton = (JButton)value;
        this.setText(String.valueOf(myButton.getText()));
        this.setEnabled(myButton.isEnabled());
        if (isSelected) {
            //System.out.println("Row = " + row);
            //System.out.println("client=" + clientIDs.get(row) + " job=" + jobIDs.get(row));
        	masterService.killJobInWorkerJobList(clientIDs.get(row), jobIDs.get(row));
        }
        return this;
    }
}*/